package de.koller.oceanFramework.plain;

import de.koller.oceanFramework.plain.Input.Key;
import de.koller.oceanFramework.tree.Sea3X;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;

/**
 * 
 * @author Fabian Koller
 */
public class PlainGameRoot extends Sea3X {

	private long time = 0;
	
	private final PlainOceanGame game;
	private Graphics2D graphics;
	
	private final Input input;
	private final Buffer<Image> buffer = new ImageBuffer();
	
	private long lastFPS = 0;
	private int currFPS = 0;
	
	private int fps = 0;
	private long usedSpace = 0;
	private long totalMemory = 0;
	
	/**
	 * 
	 * @param game
	 */
	public PlainGameRoot( PlainOceanGame game ) {
		this.game = game;
		input = new Input( game );
	}

	/**
	 * 
	 */
	@Override
	protected void init() {
		super.init();
		
		this.addChild( input );
		lastFPS = System.currentTimeMillis();
	}
	
	/**
	 * 
	 */
	@Override
	public void postChildRender() {
		super.postChildRender();
		
		graphics.setTransform( new AffineTransform() );
		if( game.getRoot().getInput().isKeyDown( Key.Key_F11 ) ) {
			graphics.setColor( Color.white );
			graphics.drawString( currFPS + " fps " + usedSpace + "MB / " + totalMemory + "MB Speicher", 2, 15 );
		}
	}
	
	/**
	 * 
	 * @param elapsedTime
	 */
	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		if( input.isKeyPressed( Key.Key_F12 ) ) {
			game.stop();
		}
		
		updateFPS();
		time++;
	}
	
	private void updateFPS() {
		if( System.currentTimeMillis() - lastFPS > 1000 ) {
			currFPS = fps;
			fps = 0;
			lastFPS += 1000;
			
			long tm = (long)(Runtime.getRuntime().totalMemory() / 1024. / 1024.);
			long fm = (long)(Runtime.getRuntime().freeMemory() / 1024. / 1024.);
			totalMemory = tm;
			usedSpace = (tm - fm);
		}
		fps++;
	}
	
	/**
	 * 
	 * @return
	 */
	public PlainOceanGame getOceanGame() {
		return game;
	}
	
	/**
	 * 
	 * @param graphics
	 */
	public void setGraphics( Graphics2D graphics ) {
		this.graphics = graphics;
	}

	/**
	 * 
	 * @return
	 */
	public Graphics2D getGraphics() {
		return graphics;
	}

	/**
	 * 
	 * @return
	 */
	public Input getInput() {
		return input;
	}

	/**
	 * 
	 * @return
	 */
	public long getUsedSpace() {
		return usedSpace;
	}

	/**
	 * 
	 * @return
	 */
	public long getTotalMemory() {
		return totalMemory;
	}

	/**
	 * 
	 * @return
	 */
	public Buffer<Image> getBuffer() {
		return buffer;
	}

	/**
	 * 
	 * @return
	 */
	public int getCurrFPS() {
		return currFPS;
	}

	/**
	 * 
	 * @return
	 */
	public long getTime() {
		return time;
	}
	
}
